from django.shortcuts import render

# Create your views here.

# TODO: 面包屑待写
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView

from .models import SKU
from .serializers import SKUListSerializer, SKUSearchSerializer


#  全文检索 第六步: 创建搜索视图集
class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUSearchSerializer


"""放弃使用APIView因为没有分页和过滤, 故使用GenericAPIView或者其子类, 根据需求是查多, 故使用ListAPIView"""

class SKUListView(ListAPIView):
    """商品列表视图"""

    # 指定过滤后后端为排序
    filter_backends = [OrderingFilter]
    # 指定那些字段进行排序
    ordering_fields = ('create_time', 'price', 'sales')

    # 指定序列化器
    serializer_class = SKUListSerializer


    # 指定查询集
    # 父类太高级了, 使用queryset无法获得前端传过来的查询字符串数据, 所以要使用get_queryset(self)方法 使用self调用view方法下的
    # args和kwargs  关键字都在kwargs字典中
    # queryset = SKU.objects.filter(is_launched=True, category_id=xxx)
    # 视图对象.kwargs属性可以拿到正则组别名的参数数据
    # 视图对象.args属性可以拿到正则组没有别名的参数数据
    def get_queryset(self):
        cat_id = self.kwargs.get('category_id')
        #                   过滤      上架            从属类别 = category_id
        return SKU.objects.filter(is_launched=True, category_id=cat_id)


"""
源码:
        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            if hasattr(self, 'get') and not hasattr(self, 'head'):
                self.head = self.get
            self.request = request
            self.args = args
            self.kwargs = kwargs
"""